import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import {
  getStudentsInfo,
  addStudent,
  deleteStudents,
  updataStudent,
} from '@/api/user'
import { reactive } from 'vue'

// 课程和学期数据（可改为接口获取）
const departmentList = [
  '数学学院',
  '外国语学院',
  '教育学院',
  '电子学院',
  '环境学院',
  '土木学院',
]
const useUserManageStore = defineStore('Manage', {
  state: () => {
    return {
      departmentList,
      tableData: [] as any[],
      queryForm: {
        username: '',
        name: '',
        deptName: '',
      },
    }
  },
  actions: {
    // 查询方法
    queryData() {
      this.tableData = this.tableData.filter((item) => {
        return (
          (!this.queryForm.username ||
            item.username.includes(this.queryForm.username)) &&
          (!this.queryForm.name || item.name.includes(this.queryForm.name)) &&
          (!this.queryForm.deptName ||
            item.deptName.includes(this.queryForm.deptName))
        )
      })
      if (this.tableData.length) {
        ElMessage({
          showClose: true,
          message: '为你找到以下数据',
          type: 'success',
        })
        //    console.log(this.tableData.length)
      } else {
        ElMessage({
          showClose: true,
          message: '找不到数据，请检查输入',
          type: 'error',
        })
      }
    },
    // 重置方法
    reset() {
      this.getStudents()
    },
    // 添加学生方法
    addStudent(student: any) {
      // console.log(Date.now())
      // id 用时间戳模拟唯一性
      // student.id = 40;
      this.tableData.unshift(student)
      console.log(this.tableData)
      addStudent(student)
    },
    // 编辑学生方法
    updateStudent(student: any) {
      console.log(student)
      const index = this.tableData.findIndex((item) => item.id === student.id)
      if (index !== -1) {
        this.tableData[index] = { ...student }
      }
      updataStudent(student)
    },
    // 单条删除
    remove(id: any) {
      console.log(id)
      this.tableData = this.tableData.filter((item) => item.id !== id)
      deleteStudents(id)
    },
    // 批量删除
    removeBatch(ids: any) {
      this.tableData = this.tableData.filter((item) => !ids.includes(item.id))
      deleteStudents(ids)
    },
    async getStudents() {
      let result = await getStudentsInfo()
      this.tableData = result.data.rows
    },
  },
})

export default useUserManageStore
